package server;

import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.code.RandomValueAuthorizationCodeServices;
import server.reids.RedisUtil;

public class MyRedisAuthorizationCodeServices extends RandomValueAuthorizationCodeServices {

    private RedisTemplate redisTemplate;

    public MyRedisAuthorizationCodeServices(RedisConnectionFactory factory ) {
        //OAuth2Authentication没有无参的构造方法，所以在json反序列化会出错,所以这里只能使用默认JDK的序列化方式。
        this.redisTemplate = new RedisTemplate();
        this.redisTemplate.setConnectionFactory(factory);
        this.redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
        this.redisTemplate.setKeySerializer(new StringRedisSerializer());
        this.redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        this.redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer());
        this.redisTemplate.afterPropertiesSet();

    }


    @Override
    protected void store(String code, OAuth2Authentication authentication) {
        redisTemplate.opsForValue().set(RedisUtil.createKey("t_code", code), authentication);
    }

    @Override
    public OAuth2Authentication remove(String code) {
        OAuth2Authentication auth = (OAuth2Authentication) redisTemplate.opsForValue().get((RedisUtil.createKey("t_code", code)));
        return auth;
    }



}
